import calendar from './lib/js-calendar-converter.mjs'

const KEY_STICKY_WALLPAPER  = 'stickyWallpaper'  // 固定壁纸开关
const KEY_PINNED_HISTORIES  = 'pinnedHistories'  // 固定历史记录列表
const KEY_WALLPAPER_URL     = 'wallpaperUrl'     // 壁纸地址
const KEY_RETRIEVE_TIME     = 'retrieveTime'     // 壁纸获取时间


class ClockWidget {
    constructor() {
        this.eleDate = document.querySelector('.date')
        this.eleTime =  document.querySelector('.time')
    }

    render() {
        this.setDateTime()
        this.startTimer()
    }

    getTime() {
        let now = new Date()
        let hours = now.getHours()
        let minutes = now.getMinutes()

        if (hours < 10) {
            hours = '0' + hours
        }

        if (minutes < 10) {
            minutes = '0' + minutes
        }

        return hours + ':' + minutes
    }

    setDateTime() {
        const lunar = calendar.solar2lunar()

        this.eleTime.innerHTML = this.getTime()
        this.eleDate.innerHTML = `${lunar.cMonth}月${lunar.cDay}日 ${lunar.ncWeek} ${lunar.IMonthCn}${lunar.IDayCn}`
    }

    startTimer() {
        return setInterval(() => {
            this.setDateTime()
        }, 1000)
    }
}

class HistoryWidget {
    pinnedHistories = []
    HistoryCount = 12

    constructor() {
        // 加载固定的历史记录
        let storedHistories = localStorage.getItem(KEY_PINNED_HISTORIES)
        if (storedHistories) {
            storedHistories = JSON.parse(storedHistories)
            this.pinnedHistories = storedHistories
        }
    }

    /**
     * 获取网页的favicon
     * @param {String} url 
     * @returns 
     */
    getFaviconUrl(url) {
        return `/_favicon/?pageUrl=${encodeURIComponent(url)}&size=32`;
    }

    /**
     * 保存固定的历史记录
     * @param {Object} history 
     */
    saveHistory(history) {
        for (let h of this.pinnedHistories) {
            if (h.id == history.id) {
                return
            }
        }

        this.pinnedHistories.push(history)
        localStorage.setItem(KEY_PINNED_HISTORIES, JSON.stringify(this.pinnedHistories))
    }

    /**
     * 删除指定的记录
     * @param {Object} history 
     * @returns 
     */
    removeHistory(history) {
        for (let i in this.pinnedHistories) {
            if (this.pinnedHistories[i].id == history.id) {
                this.pinnedHistories.splice(i, 1)
                break
            }
        }

        localStorage.setItem(KEY_PINNED_HISTORIES, JSON.stringify(this.pinnedHistories))
    }

    /**
     * 渲染历史记录标签
     * @param {Object} history 
     */
    renderHistoryEl(history, saved = false) {
        const that = this

        function eventPinClick(event) {
            event.stopPropagation()
            event.preventDefault()
            that.saveHistory(history)

            this.classList.add('pinned')
            this.title = '取消固定'
            this.removeEventListener('click', eventPinClick)
            this.addEventListener('click', eventUnpinClick)
        }

        function eventUnpinClick(event) {
            event.stopPropagation()
            event.preventDefault()
            that.removeHistory(history)

            this.classList.remove('pinned')
            this.title = '固定'
            this.removeEventListener('click', eventUnpinClick)
            this.addEventListener('click', eventPinClick)
        }

        let divHistory = document.createElement('div')
        divHistory.classList.add('history')

        let linkHistory = document.createElement('a')
        linkHistory.classList.add('history-link')
        linkHistory.href = history.url
        linkHistory.target = '_self'

        let imgPin = document.createElement('img')
        imgPin.classList.add('img-stick')
        imgPin.width = 16
        imgPin.height = 16
        imgPin.src = 'images/ico-pin.png'
        
        if (saved) {
            imgPin.title = '取消固定'
            imgPin.classList.add('pinned')
            imgPin.addEventListener('click', eventUnpinClick)
        } else {
            imgPin.title = '固定'
            imgPin.addEventListener('click', eventPinClick)
        }
        
        linkHistory.appendChild(imgPin)

        let imgHistory = document.createElement('img')
        imgHistory.classList.add('history-icon')
        imgHistory.src = this.getFaviconUrl(history.url)
        imgHistory.width = 32
        imgHistory.height = 32
        imgHistory.alt = ''
        linkHistory.appendChild(imgHistory)

        let titleSpan = document.createElement('span')
        titleSpan.classList.add('history-title')
        titleSpan.innerText = history.title

        divHistory.appendChild(linkHistory)
        divHistory.appendChild(titleSpan)
        document.querySelector('.histories').appendChild(divHistory)
    }

    render() {
        if (this.pinnedHistories.length > 0) {
            for (let history of this.pinnedHistories) {
                this.renderHistoryEl(history, true)
            }
        }

        if (this.pinnedHistories.length >= this.HistoryCount) {
            return
        }

        const historyIDs = new Map()
        for (let h of this.pinnedHistories) {
            historyIDs.set(h.id, true)
        }

        chrome.history.search({text: ''}, histories => {
            // 查找手动输入访问最多的12个网址
            let count = 0
            for (let history of histories) {
                if (historyIDs.has(history.id)) {
                    continue
                }

                this.renderHistoryEl(history)

                count++

                if (count >= (this.HistoryCount - this.pinnedHistories.length)) {
                    break
                }
            }
        })
    }
}

class WallpaperWidget {
    constructor() {
        this.url = localStorage.getItem(KEY_WALLPAPER_URL)
    }

    async retrieve() {
        try {
            const res = await fetch('https://api.codelife.cc/wallpaper/random?lang=cn')

            if (res.status >= 400) {
                return null
            }

            const result = await res.json()
            if (result.code != 200) {
                return null
            }

            this.url = result.data

            const lunar = calendar.solar2lunar()
            localStorage.setItem(KEY_WALLPAPER_URL, this.url)
            localStorage.setItem(KEY_RETRIEVE_TIME, lunar.date)

            return this.url
        } catch(e) {
            console.error(e)
        }

        return null
    }

    setBackground(url) {
        document.querySelector('.wrapper').style.backgroundImage = `url(${url})`
    }

    refresh() {
        this.retrieve().then(res => {
            if (!res) {
                return
            }

            this.setBackground(res)
        })
    }

    render() {
        let lastTime = localStorage.getItem(KEY_RETRIEVE_TIME)
        let sticky = localStorage.getItem(KEY_STICKY_WALLPAPER) 
        let lunar = calendar.solar2lunar()

        if ((!sticky || sticky == '0') && lastTime != lunar.date) {
            this.retrieve().then(res => {
                if (res) {
                    this.setBackground(res)
                }
            })
            return
        }

        if (this.url) {
            this.setBackground(this.url)
        }
    }
}

function registerSearchInputEvent() {
    document.querySelector('#input-main').addEventListener('keyup', function(e) {
        let inputMain = this;
        let keywords = inputMain.value;
        console.log('关键字', keywords)

        let elDropdown = document.querySelector('.dropdown')
        elDropdown.innerHTML = ''

        if (!keywords) {
            return
        }

        // 按回车直接搜索
        if (e.keyCode == 13) {
            chrome.tabs.create({
                url: `https://www.baidu.com/s?wd=${keywords}`,
            })
            inputMain.value = ''
            return
        }

        // 搜索书签
        chrome.bookmarks.search(keywords, bookmarks => {
            if (!bookmarks || bookmarks.length <= 0 || bookmarks.length > 10) {
                return
            }

            for (let bookmark of bookmarks) {
                let li = document.createElement('li')
                li.classList.add('item')
                li.innerHTML = `<div class="item-container"><h4>${bookmark.title}</h4><p>${bookmark.url}</p></div>`
                li.addEventListener('click', () => {
                    chrome.tabs.create({
                        url: li.childNodes[0].childNodes[1].innerText,
                    })

                    inputMain.value = ''
                    elDropdown.style.display = 'none'
                })

                elDropdown.appendChild(li)
            }

            elDropdown.style.display = 'block'
        })
    })
}

function registerWallpaperEvent() {
    document.querySelector('.toolbar-action.action-refresh').addEventListener('click', function(e) {
        let wallpaper = new WallpaperWidget()
        wallpaper.refresh()
    })
    

    document.querySelector('.toolbar-action.action-sticky').addEventListener('click', function(e) {
        let image = this.querySelector('.toolbar-icon')
        if (image.classList.contains('icon-like')) {
            image.src = 'images/ico-like-fill.png'
            image.classList.remove('icon-like')
            image.classList.add('icon-like-fill')
            localStorage.setItem(KEY_STICKY_WALLPAPER, '1')
        } else {
            image.src = 'images/ico-like.png'
            image.classList.remove('icon-like-fill')
            image.classList.add('icon-like')
            localStorage.setItem(KEY_STICKY_WALLPAPER, '0')
        }
    })
}

function registerEvent() {
    // 注册搜索框事件
    registerSearchInputEvent()

    // 注册壁纸事件
    registerWallpaperEvent()
}

function init() {
    // 渲染壁纸
    let wallpaper = new WallpaperWidget()
    wallpaper.render()

    // 渲染时钟
    let clock = new ClockWidget()
    clock.render()
    
    // 渲染历史记录
    let history = new HistoryWidget()
    history.render()

    // 初始化固定壁纸图标状态
    let iconLike = document.querySelector('.toolbar-icon.icon-like')
    if (localStorage.getItem(KEY_STICKY_WALLPAPER) == '1') {
        iconLike.src = 'images/ico-like-fill.png'
    }

    // 注册事件
    registerEvent()
}

init()